require 'sinatra'
require 'dm-core'

enable :sessions

# Configure DataMapper to use the App Engine datastore 
DataMapper.setup(:default, "appengine://auto")

# Create your model class
class Product
  include DataMapper::Resource
  
  property :id, Serial
  property :name, Text
  property :completed_at, DateTime
  
end

class Mylist
  include DataMapper::Resource
  
  property :id, Serial
  property :product, String
  property :usuario, String
  property :checked, Boolean
end

# Make sure our template can use <%=h
helpers do
  include Rack::Utils
  alias_method :h, :escape_html
end

before do
  if session[:usuario] && !session[:redirect]
     session[:redirect]=true 
     redirect "/"
   else
     if params[:id]=="1"
        session[:usuario]=true   
     end
   end
end

get '/' do
  # Just list all the shouts
  @products = Product.all
  @product_list = Mylist.all
  erb :index
end

post '/' do
  # Create a new shout and redirect back to the list.
  product = Product.create(:name => params[:name])
  redirect '/'
end

delete '/:id' do
  product = Product.get(params[:id]).destroy  
  redirect "/"
end


post '/mylist' do
  #@product_list = Product.get(params[:name])
  @product_list = Mylist.create(:product => params[:id], :usuario => 'marcio', :checked => false)

  redirect '/'
end

delete '/mylist/delete/:id' do
  product = Mylist.get(params[:id]).destroy  
  redirect "/"
end

# edit task
get '/task/:id/edit' do
  erb :edit
end

# update list
put '/:id' do
  product = Mylist.get(params[:id])
  Mylist.completed_at = params[:completed] ?  Time.now : nil
  product.name = (params[:name])
end

post '/mylist/checked/:id' do
  product = Mylist.get(params[:id])
  product.checked = ! product.checked 
  product.save
  
  redirect '/'
end